package com.sskj.xgja.api;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.sskj.base.api.OtherLoginException;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * create by Hey at 2018/6/28 15:30
 */
public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final Type type;

    GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        try {
            if (response.contains("status")) {
                HttpResponse httpResult = gson.fromJson(response, HttpResponse.class);
                if (httpResult.getStatus() == 404) {
                    throw new OtherLoginException();
                } else if (httpResult.getStatus() != 200) {
                    throw new ServiceException(httpResult, httpResult.getMsg());
                } else {
                    return gson.fromJson(response, type);
                }
            } else {
                return gson.fromJson(response, type);
            }
        } catch (JsonSyntaxException e) {
            if (response.contains("code") && response.contains("msg")) {
                throw new ServiceException(response);
            }
            return (T) response;
        } catch (ClassCastException e) {
            throw new ServiceException(response);
        } finally {
            value.close();
        }
    }
}
